//就shift+alt+F调了一下样式，其他什么都没动
import { citycode2plainJson } from '@/components/CityCode/citycode';
import type { ResponseData, ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import { message } from 'antd';
import { request } from 'umi';
import type {
  Zone,
  ZoneCreationItem,
  ZoneDetailItem,
  ZoneTableListItem,
  ZoneUpdateItem,
} from './data';

type Pagination = { page?: number; pageSize?: number };

/**
 * 添加停车区域
 * 0 - 成功
 * @param params
 */
export async function addZone(params: ZoneCreationItem): Promise<ResponseData<Zone>> {
  let district: string = '';

  if (params?.district && params?.district?.length > 0) {
    district = params?.district[params?.district.length - 1];
  }

  const res: ResponseData<any> = await request('/zone/zone/add', {
    method: 'POST',
    data: {
      ...params,
      space_total_count: params.space_total_count || 0,
      lat: params.location?.lat || 0.0,
      lng: params.location?.lng || 0.0,
      city_code: district || '',
      scheme_id: params.scheme?.id,
      open_time: params.open_time?.map((item) => item.format('HH:mm')).join('-'),
      reserve_scheme_id: params.reserve_scheme?.id,
    },
  });
  return res;
}

/**
 * 获取停车区域列表
 * @param params
 */
export async function getZoneSelectionList(
  params: Pagination & { name?: string; no?: string },
): Promise<RequestData<ZoneTableListItem>> {
  const res: ResponsePaginationData<{
    id: string;
    name?: string;
  }> = await request('/zone/zone/list', {
    params: {
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      query: params.name,
    },
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list,
  };
}

/**
 * 获取停车区域列表
 * @param params
 */
export async function queryZoneList(
  params: Pagination & { name?: string; no?: string },
): Promise<RequestData<ZoneTableListItem>> {
  const res: ResponsePaginationData<{
    scheme?: { id: string; name: string };
    id: string;
    name?: string;
    no?: string;
    address?: string;
    type?: string;
    cityCode?: number;
    reserve_scheme?: { id: string; name: string };
  }> = await request('/zone/zone/list', {
    params: {
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      query: params.name,
      no: params.no,
    },
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map((item) => ({
      ...item,
      district: citycode2plainJson(String(item.cityCode)).map((cc) => cc.code),
    })),
  };
}

/**
 * 获取单个停车区域信息
 * @param params
 */
export async function showZoneDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: ZoneDetailItem }> {
  const res: ResponseData<{
    id: string;
    name: string;
    no: string;
    address: string;
    cityCode: number;
    scheme: { id: string; name: string };
    lng: number;
    lat: number;
    type: string;
  }> = await request(`/zone/zone/${params.id}`);
  if (!res || res.code !== SUCCESS_CODE || !res.data) {
    message.error('获取失败');
    return { success: false };
  }

  const { data } = res;

  const district = citycode2plainJson(String(data.cityCode)).map((cc) => cc.code);

  return {
    success: true,

    data: {
      ...data,
      district: district || '',
      location: { lng: data.lng, lat: data.lat },
    },
  };
}

/**
 * 更新停车区域
 * @param params
 */
export async function updateZone(params: ZoneUpdateItem): Promise<ResponseData<any>> {
  const res: ResponseData<any> = await request('/zone/zone/update', {
    method: 'POST',
    data: {
      ...params,
      ...params.location,
      scheme_id: params.scheme?.id,
      reserve_scheme_id: params.reserve_scheme?.id,
      open_time: params.open_time?.map((item) => item.format('HH:mm')).join('-'),
      city_code: params.district ? Number(params.district[params.district.length - 1]) : undefined,
      space_total_count: params.space_total_count || 0,
    },
  });

  if (!res || res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
  return res;
}

// 删除车场
export async function removeZone(params: { id: string }): Promise<void> {
  const res: ResponseData<any> = await request(`/zone/zone/${params.id}`, { method: 'DELETE' });

  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}

// 绑定收费方案
export async function setSchemeRule(params: {
  id: string;
  record: { id: string };
}): Promise<ResponseData<any>> {
  const { record } = params;
  return request(`/zone/zone/config/scheme`, {
    method: 'POST',
    data: {
      scheme_id: record.id,
      zoneId: params.id,
    },
  });
}

// 绑定收费方案
export async function setReserveScheme(params: {
  id: string;
  record: { id: string };
}): Promise<ResponseData<boolean>> {
  const { record } = params;
  return request(`/zone/zone/config/set_reserve_scheme`, {
    method: 'POST',
    data: {
      scheme_id: record.id,
      zoneId: params.id,
    },
  });
}
